package com.wenchao.libnettytcp;

import android.util.Log;

import com.wenchao.libnettytcp.listener.NettyClientListener;
import com.wenchao.libnettytcp.status.ConnectState;

import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ProjectName:
 * @Package: com.zzcyi.rubikcubecharger.netty
 * @ClassName: NettyManager
 * @Description: java类作用描述
 * @Author: qiangSir
 * @CreateDate: 2020/5/22 14:50
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/5/22 14:50
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class NettyManager {

    private static NettyManager nettyManager;
    private NettyTcpClient mNettyTcpClient;
    private String id;
    private Timer timer;

    public NettyManager() {
    }

    public static NettyManager getInstance() {
        if (nettyManager == null) {
            nettyManager = new NettyManager();
        }
        return nettyManager;
    }

    private OnReceiver mOnreceiver;

    public interface OnReceiver {

        void receiver(byte[] msg);

        void connected();

        void disConnected();
    }

    public void setOnReceiver(OnReceiver mOnreceiver) {
        this.mOnreceiver = mOnreceiver;
    }

    private final NettyClientListener<byte[]> nettyClientListener = new NettyClientListener<byte[]>() {

        @Override
        public void onMessageResponseClient(byte[] msg, int index) {
            if (mOnreceiver != null) {
                mOnreceiver.receiver(msg);
            }
        }

        @Override
        public void onClientStatusConnectChanged(int statusCode, int index) {
            Log.e("TAG", "onClientStatusConnectChanged: >>>>>>>>>>>>>>>>>>>>" + statusCode);
            if (statusCode == ConnectState.STATUS_CONNECT_SUCCESS) {
                // 连接成功
                if (mNettyTcpClient != null) {
                    mNettyTcpClient.sendMsgToServer(id);
                }

                if (mOnreceiver != null) {
                    mOnreceiver.connected();
                }
            } else if (statusCode == ConnectState.STATUS_CONNECT_FAILED) {
                // 连接失败
                Log.e("TAG", "连接失败");
            } else if (statusCode == ConnectState.STATUS_CONNECT_CLOSED ||
                    statusCode == ConnectState.STATUS_CONNECT_ERROR) {
                if (mOnreceiver != null) {
                    mOnreceiver.disConnected();
                }
            }
        }
    };

    public void connectTcp(String ip, int port) {
        this.connectTcp(ip, port, 10, Integer.MAX_VALUE);
    }

    public void connectTcp(String ip, int port, int timeOut, int retryTime) {
        this.id = "{\"client_id\":\"111\"}";
        if (mNettyTcpClient == null) {
            mNettyTcpClient = new NettyTcpClient.Builder()
                    .setHost(ip)    //设置服务端地址
                    .setTcpPort(port) //设置服务端端口号
                    .setMaxReconnectTimes(retryTime)    //设置最大重连次数
                    .setConnectTimeOut(timeOut * 1000)
                    .setReconnectIntervalTime(5 * 1000L)    //设置重连间隔时间。单位：秒
                    .setSendheartBeat(true) //设置是否发送心跳
                    .setHeartBeatInterval(60) //设置心跳间隔时间。单位：秒
                    .setHeartBeatData(id) //设置心跳数据，可以是String类型，也可以是byte[]，以后设置的为准
                    .setIndex(0)    //设置客户端标识.(因为可能存在多个tcp连接)
//                .setPacketSeparator("#")//用特殊字符，作为分隔符，解决粘包问题，默认是用换行符作为分隔符
                    .setMaxPacketLong(4096)//设置一次发送数据的最大长度，默认是1024
                    .build();
            mNettyTcpClient.setListener(nettyClientListener); //设置TCP监听
        }
        mNettyTcpClient.connect();
    }

    public boolean isConnect() {
        if (mNettyTcpClient != null) {
            return mNettyTcpClient.getConnectStatus();
        }
        return false;
    }

    public void disconnect() {
        if (mNettyTcpClient != null) {
            mNettyTcpClient.disconnect();
            mNettyTcpClient = null;
        }
    }

    public void sendMsg(byte[] msg) {
        if (mNettyTcpClient != null) {
            boolean sendByteToServer = mNettyTcpClient.sendByteToServer(msg);
        }
    }

    public void timerSendCmd(byte[] bytes) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mNettyTcpClient != null) {
                    mNettyTcpClient.sendByteToServer(bytes);
                }

            }
        }, 0, 3000);
    }

}
